from PyQt4.QtNetwork import QTcpSocket, QTcpServer
from PyQt4 import QtCore
from PyQt4.QtCore import QString, QObject
from Vector import *

class Connection(QObject):
	def __init__(self, parent=None):
		self.socket = QTcpSocket()
		self.server = QTcpServer()
		self.hostname = ""
		self.parent = parent
		self.socket.disconnected.connect(self.disconnected)
		self.socket.readyRead.connect(self.receive)

	def connect(self, host, port):
		self.hostname = host
		self.socket.connectToHost(host, port)
		if (self.socket.waitForConnected(1000)):
			if (self.socket.state() == QTcpSocket.ConnectedState):
				self.parent.initializeGame()

	def cancel(self):
		self.socket.close()
		self.server.close()

	def listen(self):
		self.server.listen()
		self.server.newConnection.connect(self.connectionRequest)
		
	def getServerPort(self):
		return self.server.serverPort()
	
	def connectionRequest(self):
		self.socket = self.server.nextPendingConnection()
		if (self.socket.state() == QTcpSocket.ConnectedState):
			self.server.close()
			self.socket.readyRead.connect(self.receive)
			self.socket.disconnected.connect(self.disconnected)
			self.parent.initializeGame()
			self.syncBall()
		
	def disconnected(self):
		self.parent.GlWidget.hide()
		self.parent.winLoseWidget.hide()
		self.parent.widget.show()
		self.parent.clientCancelButtonClicked()
		self.parent.serverCancelButtonClicked()
		
	def sendRacketPosition(self, values):
		if (self.socket.state() == QTcpSocket.ConnectedState):
			text = ""
			for value in values:
				text += str(value) + ";"
			text = QString(text[:-1]) + "$"
			self.socket.write(QString(text).toAscii())

	def sendRacketAttack(self):
		if (self.socket.state() == QTcpSocket.ConnectedState):
			text = "a$"
			self.socket.write(QString(text).toAscii())

	def syncBall(self):
		if (self.socket.state() == QTcpSocket.ConnectedState):
			text = "b"
			pos, vel = self.parent.GlWidget.ball.position.list(), self.parent.GlWidget.ball.velocity.list()
			text += str(pos[0]) + ";" + str(pos[1]) + ";" + str(pos[2]) + ";"
			text += str(vel[0]) + ";" + str(vel[1]) + ";" + str(vel[2])
			text = QString(text) + "$"
			self.socket.write(QString(text).toAscii())

	def sendPoint(self,player, rule):
		if (self.socket.state() == QTcpSocket.ConnectedState):
			text = "p"
			text += str(player)
			text += str(rule)
			text = QString(text) + "$"
			self.socket.write(QString(text).toAscii())

	def sendRestart(self):
		if (self.socket.state() == QTcpSocket.ConnectedState):
			self.socket.write(QString("r$").toAscii())
			
	def receive(self):
		text = QString(self.socket.readAll())
		lines = text.split("$")
		for line in lines:
			if (line != ""):
				# racketAttack
				if (line[0] == "a"):
					self.parent.GlWidget.otherRacket.attack()
				# syncBall:
				elif (line[0] == "b"):
					line = line[1:]
					strings = line.split(";")
					values = []
					oks = True
					for value in strings:
						temp, ok = value.toFloat()
						values += [temp]
						if (not ok):
							oks = False
					if (oks):
						self.parent.GlWidget.ball.position = Vector(-values[0], values[1], -values[2])
						self.parent.GlWidget.ball.velocity = Vector(-values[3], values[4], -values[5])
						self.parent.GlWidget.useGravity = True
						self.parent.GlWidget.lastPlayer = 1
						self.parent.GlWidget.mySideBounce = False
				elif (line[0] == "p"):
					player = int(line[1])
					rule = int(line[2])
					self.parent.GlWidget.addRemoteScorePoint(player, rule)
				elif (line[0] == "r"):
					self.parent.restartGame()
				else:
					strings = line.split(";")
					values = []
					oks = True
					for value in strings:
						temp, ok = value.toFloat()
						values += [temp]
						if (not ok):
							oks = False
					if (oks):
						self.parent.GlWidget.moveOpponentRacket(values)
